package graph.day13;

import java.util.Arrays;

public class HeapSort {

    public static void sort(int[] arr) {
        heapify(arr, arr.length);
        for (int i = arr.length - 1; i > 0; i--) {
            swap(arr, 0, i);
            down(arr, 0, i);
        }
    }


    // 建堆 O(n)
    private static void heapify(int[] arr, int size) {
        for (int i = size / 2 - 1; i >= 0; i--) {
            down(arr, i, size);
        }
    }

    // 下潜
    private static void down(int[] arr, int parent, int size) {
        while (true) {
            int left = 2 * parent + 1;
            int right = 2 * parent + 2;
            int max = parent;
            if (left < size && arr[left] > arr[max]) {
                max = left;
            }
            if (right < size && arr[right] > arr[max]) {
                max = right;
            }
            if (max == parent) {
                break;
            }
            swap(arr, parent, max);
            parent = max;
        }
    }

    // 交换
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        int[] arr = {5, 3, 8, 4, 2};
        System.out.println(Arrays.toString(arr));
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
